package com.test.murali;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JokesService {
	
	private DefaultHttpClient httpClient;
	private HttpGet get_request;
	private HttpContext localContext;
	
	public JokesService(){
		httpClient = new DefaultHttpClient();
		localContext= new BasicHttpContext();
	}
	
	public Joke getJoke(int id){
		String uri="http://www.speedogames.com:3000/jokes/" + id + ".json";
		get_request=new HttpGet(uri);

		HttpResponse response;
		Joke joke = new Joke();
		try {
			response = httpClient.execute(get_request,localContext);
			InputStream inStream= response.getEntity().getContent();
			String result = convertStreamToString(inStream);

			JSONObject jsonReturn = new JSONObject(result);
			
			JSONObject jokeJson = jsonReturn.getJSONObject("joke");

			joke.setDescription(jokeJson.getString("desc"));
			joke.setId(jokeJson.getInt("id"));

	    	Log.i("Json returned :" , jsonReturn.toString());


		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return joke;
	}
	
	private static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

}
